const Models = require('./../models')
const jwt = require('jwt-simple')

module.exports = function (req, res, next) {
  var token = req.headers.authorization
  req.userInfo = {expired: null, username: null, avatar: null}
  if (token) {
    try {
      var decoded = jwt.decode(token, 'WTMSB')
      if (decoded.exp <= Date.now()) {
        req.userInfo.expired = true
        next()
      } else {
        if (req._parsedUrl.pathname === '/api/preserveLoginStatus') {
          console.log(1)
          Models.UsersModel.findOne({username: decoded.iss}, function (err, user) {
            if (err) {
              res.json({status: 'ERROR', payload: 'SERVERERROR'})
              return
            } else {
              req.userInfo.expired = false
              req.userInfo.username = user.username
              req.userInfo.avatar = user.avatar
              next()
            }
          })
        } else {
          req.userInfo.expired = false
          next()
        }
      }
    } catch (err) {
      console.log(err)
      return next()
    }
  } else {
    next()
  }
}
